//
//  MyMiDouViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/6/17.
//

#import "MyMiDouViewController.h"
#import "MidouTopView.h"
#import "MidouTableViewCell.h"
#import "MidouListViewController.h"
#import "MiDouModel.h"
#import <RMStore/RMStore.h>
@interface MyMiDouViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic , strong) MidouTopView * topView;
@property (nonatomic , strong) HeaderView * addButton;
@property (nonatomic , strong) MiDouModel * seletedModel;
@end

@implementation MyMiDouViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.zx_navTitle = SQNSLocalString(@"我的觅豆");
    WS(weakSelf);
    [self zx_setRightBtnWithText:SQNSLocalString(@"觅豆明细") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        MidouListViewController * vc = [[MidouListViewController alloc]init];
        [weakSelf SQ_pushViewControllerFull:vc];
    }];
    self.zx_navBar.zx_rightBtn.zx_fixWidth = 70;
    // Do any additional setup after loading the view.
}
- (void)SQ_UIViewForSelfView{

    self.tableView.tableHeaderView = self.topView;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(TopHeight, 0, 0, 0));
    }];
    [self.view addSubview:self.addButton];
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.height.mas_equalTo(54);
            make.width.mas_equalTo(270);
            make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-60);
    }];
    YYLabel * label3 = [[YYLabel alloc]initWithFrame:CGRectMake(SCREEN_WIDETH/2.f-110, SCREEN_HEIGHT- FootHeight-40, 220, 30)];
    label3.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    label3.textAlignment = NSTextAlignmentCenter;
    label3.numberOfLines = 0;
    [self.view addSubview:label3];
    NSDictionary *attributes = @{NSFontAttributeName:FONT_MEDIUM(12) , NSForegroundColorAttributeName: SQColor(@"#DBDBDB")};
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:SQNSLocalString(@"点击购买既代表同意《觅豆充值协议》") attributes:attributes];
    WS(weakSelf);
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:SQNSLocalString(@"《觅豆充值协议》")] color:SQColor(@"#F835E5") backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  MDXY;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSRange range1=[[text string]rangeOfString:SQNSLocalString(@"《觅豆充值协议》")];
    YYTextDecoration* deco=[YYTextDecoration decorationWithStyle:(YYTextLineStyleSingle) width:[NSNumber numberWithInt:0] color:[UIColor whiteColor]];
    [text yy_setTextUnderline:deco range:range1];
    label3.attributedText = text;
    
//
    
    [self.topView SQ_topReload];
    [self SQ_Header];
}
- (void)SQ_Header{
    [self.tableView reloadData];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [HttpTool post:Url9 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
       
        [self.jsonArray removeAllObjects];
        NSArray * array = [MiDouModel mj_objectArrayWithKeyValuesArray:httpModel.data];
        [self.jsonArray addObjectsFromArray:array];
        if (array.count > 0) {
         self.seletedModel = array.firstObject;
         self.seletedModel.isseleted = YES;
            self.addButton.text  = [NSString stringWithFormat:@"%@%@",SQNSLocalString(@"立即充值"),self.seletedModel.name];
         [self SQ_RMStore];
        }
        [self.tableView reloadData];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}
-(void)SQ_RMStore{
 
    NSMutableArray * array = [[NSMutableArray alloc]init];
    [self.jsonArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MiDouModel * model = (MiDouModel*)obj;
        if ([model.appleId isNotEmpty]) {
            [array addObject:model.appleId];
        }
    }];
     [[RMStore defaultStore] requestProducts:[NSSet setWithArray:array] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        if([products count] == 0){
            DTLog(@"--------------没有商品------------------");
            return;
        }
        DTLog(@"内购商品列表------%@",products);
    } failure:^(NSError *error) {
        DTLog(@"--------------请求商品失败--------------%@----",error);
    }];
}

-(void)SQ_addMidou{
   
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    WS(weakSelf);
     [[RMStore defaultStore] addPayment:self.seletedModel.appleId success:^(SKPaymentTransaction *transaction) {
            [weakSelf checkIAPResultWithtransactionReceiptblock];
        } failure:^(SKPaymentTransaction *transaction, NSError *error) {
            [YJProgressHUD showMsgWithoutView: SQNSLocalString(@"交易失败")];
         
    }];
    
}
- (void)checkIAPResultWithtransactionReceiptblock
{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        if (receiptURL) {
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
            DTLog(@"%@",receiptData);
            NSString *encodeStr = [receiptData base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithLineFeed];
             NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:encodeStr forKey:@"certificate"];
             [YJProgressHUD SQ_showMsgWithoutView:@""];
            [HttpTool post:Url10 paramDic:dic successBlock:^(BaseModel * _Nullable httpModel) {
                
                for (SKPaymentTransaction *aTransaction in [[SKPaymentQueue defaultQueue] transactions]) {
                    [[SKPaymentQueue defaultQueue]finishTransaction:aTransaction];
                }
                [self SQ_goumaichenggong];
            } andFailBloc:^(BaseModel * _Nullable httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
        }else{
            [YJProgressHUD hide];
           
        }
}
-(void)SQ_goumaichenggong{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [HttpTool post:Url6 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        [MeModel SQ_setuserModel:httpModel];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
    }];
    SQCustomButton * btn = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(120, 120) midmargin:20];
//    btn.backgroundColor = self.view.backgroundColor;
    btn.text = SQNSLocalString(@"购买成功");
    btn.textColor = UIColor.whiteColor;
    btn.font = FONT_MEDIUM(20);
    btn.image = SQGetImage(@"插画");
    LSTPopView * pop = [LSTPopView initWithCustomView:btn
                                           parentView:nil
                                             popStyle:LSTPopStyleFade dismissStyle:LSTDismissStyleFade];
    pop.hemStyle = LSTHemStyleCenter;
    pop.showTime = 2;
    pop.bgAlpha = 1;
//    pop.bgColor = SQColor333333;
    [pop pop];
    WS(weakSelf);
    [pop setPopViewDidDismissBlock:^{
        [weakSelf SQ_popViewVC];
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     return self.jsonArray.count;
        
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MidouTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MidouTableViewCell"];
    if (!cell) {
        cell = [[MidouTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"MidouTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = [self.jsonArray objectAtIndex:indexPath.item];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MiDouModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    if ([model.name isEqualToString:self.seletedModel.name]) {
        return 90;
    }
   return  68;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.seletedModel.isseleted = NO;
    self.seletedModel = [self.jsonArray objectAtIndex:indexPath.item];
    self.seletedModel.isseleted = YES;
    [self.tableView reloadData];
    self.addButton.text  = [NSString stringWithFormat:@"%@%@",SQNSLocalString(@"立即充值"),self.seletedModel.name];
    
}
- (MidouTopView *)topView{
    if (!_topView) {
        _topView = [[MidouTopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, 170)];
    }
    return _topView;
}

- (HeaderView *)addButton{
    if (!_addButton) {
        _addButton = [[HeaderView alloc]init];
        _addButton.image = @"矩形";
        _addButton.colorString = @"#FFFFFF";
        [_addButton.btn addTarget:self action:@selector(SQ_addMidou) forControlEvents:UIControlEventTouchUpInside];
        _addButton.layer.cornerRadius = 28;
        _addButton.layer.masksToBounds = YES;
        _addButton.text = SQNSLocalString(@"立即充值");
        _addButton.font = FONT_MEDIUM(18);
    }
    return _addButton;
}

@end
